package com.ktjiaoyu.crm.web.controller;

import com.ktjiaoyu.crm.entity.Right;
import com.ktjiaoyu.crm.entity.Role;
import com.ktjiaoyu.crm.entity.User;
import com.ktjiaoyu.crm.service.IRoleService;
import com.ktjiaoyu.crm.service.IUserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色控制器
 * @author Administrator
 */
@Controller
public class RoleController {
    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;

    @RequestMapping(value = "/role/list")
    public String list(Model model, String roleName,
                       @RequestParam(required = false, defaultValue = "1") int pageIndex){
        Sort sort = new Sort(Sort.Direction.ASC, "roleId");
        Pageable pageable = PageRequest.of(pageIndex-1, 5, sort);
        Page<Role> rolePager = roleService.findRoles(roleName, pageable);
        model.addAttribute("rolePager", rolePager);
        model.addAttribute("roleName", roleName);
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("roles", roles);
        return "role/list";
    }

    @RequestMapping(value = "/role/add")
    public String add(Model model){
        //查询所有角色
        List<Right> rights = roleService.findAllRights();
        model.addAttribute("rights",rights);
        return "role/add";
    }

    @RequestMapping(value = "/role/save")
    public String save(Role role,String[] rightCodes){
        if(rightCodes!=null){
            for (String rightCode:rightCodes){
                Right right =new Right();
                right.setRightCode(rightCode);
               role.getRights().add(right);
            }
        }
        roleService.saveRole(role);
        return "redirect:/role/list";
    }

    @RequestMapping(value = "/role/edit")
    public String edit(Long roleId,Model model){
       Role role = roleService.getRole(roleId);
        model.addAttribute("role",role);

       List<Right> roleRights = roleService.findRightsByRole(role);
        model.addAttribute("roleRights",roleRights);

       List<Right> rights = roleService.findAllRights();
       model.addAttribute("rights",rights);


        return "role/edit";
    }
}
